package com.indusfo.spc.service.impl;

import org.apache.commons.lang3.StringUtils;
import com.indusfo.spc.exception.GlobalException;
import com.indusfo.spc.exception.ModifyFailedException;
import com.indusfo.spc.exception.ParamsErrorException;
import com.indusfo.spc.mapper.BadphenoMapper;
import com.indusfo.spc.mapper.BadphenoTypeMapper;
import com.indusfo.spc.pojo.Badpheno;
import com.indusfo.spc.pojo.BadphenoType;
import com.indusfo.spc.service.BadphenoTypeService;
import com.indusfo.spc.vo.JSONObject;
import com.indusfo.spc.vo.XCommonUtil;
import com.indusfo.spc.vo.XTreeNode;
import com.indusfo.spc.vo.XTreeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @ProjectName: IEIS2-COM
 * @Package: com.indusfo.spc.service.impl
 * @ClassName: BadphenoTypeServiceImpl
 * @Author: 熊冰
 * @Description: 不良现象类型 业务层
 * @Date: 2019/8/20 10:18
 * @Version: 1.0
 */
@Service
public class BadphenoTypeServiceImpl implements BadphenoTypeService {

    //日志记录
    private static final Logger logger = LoggerFactory.getLogger(BadphenoTypeServiceImpl.class);

    @Autowired
    private BadphenoTypeMapper badphenoTypeMapper;
    @Autowired
    private BadphenoMapper badphenoMapper;
    //查询
    @Override
    public JSONObject listBadphenoType(BadphenoType badphenoType) {
        try {
            // 获取一页显示多少行
            Integer pagesize = badphenoType.getPagesize();
            // 获取查询第几页
            Integer pageindex = badphenoType.getPageindex();
            //初始值
            // 若不为空计算从第几条开始查询
            if (pagesize != null && pageindex != null) {
                badphenoType.setIncept(pagesize * (pageindex - 1));
            }
            // 为空进行多条的分页查询
            // 调用Mapper分页查询方法
            List<BadphenoType> listForPage = badphenoTypeMapper.selectAllBadphenoType(badphenoType);
            // 判断是否查询到数据
            if (listForPage.isEmpty()) {
                return JSONObject.oK("没有查询到数据", listForPage, 0);
            }
            // 查询有多少条数据条数
            if (pagesize != null && pageindex != null) {
                Integer count = badphenoTypeMapper.countBadphenoType(badphenoType);
                return JSONObject.oK(listForPage, count);
            }
            return JSONObject.oK(listForPage.get(0));
        } catch (GlobalException e) {
            // 捕获异常,打印并返回数
            logger.error(e.getMessage(), e);
            return JSONObject.build(500, e.getMessage());
        }
    }

    //新增
    @Override
    public JSONObject insertOrUpdateBadphenoType(BadphenoType badphenoType) {
        try {
            if (badphenoType.getBadphenoTypePid() == null) {
                badphenoType.setBadphenoTypePid(0);
            }
            if (badphenoType.getDataState() == null) {
                badphenoType.setDataState(1);
            }
            JSONObject checkParamsNotRepeatJson = checkParamsNotRepeat(badphenoType);
            if (checkParamsNotRepeatJson.isOk()) {
                if (badphenoType.getBadphenoTypeId() != null) {// 有id,做更新
                    validate(badphenoType);
                    Integer row = badphenoTypeMapper.updateByPrimaryKeySelective(badphenoType);
                    if (row == 0) {
                        throw new ModifyFailedException("编辑不良现象类型失败");
                    }
                    return JSONObject.oK("编辑成功", badphenoType.getBadphenoTypeId());
                } else {// 没id,做新增
                    // 校验传入参数
                    validate(badphenoType);
                    Integer row = badphenoTypeMapper.insertSelective(badphenoType);
                    if (row == 0) {
                        throw new ModifyFailedException("新增不良现象类型失败");
                    }
                    return JSONObject.oK("新增成功", badphenoType.getBadphenoTypeId());
                }
            } else {
                throw new ParamsErrorException(checkParamsNotRepeatJson.getMsg());
            }
        } catch (GlobalException e) {
            logger.error(e.getMessage());
            return JSONObject.build(500, e.getMessage());
        }
    }

    //删除
    @Override
    public JSONObject deleteBadphenoType(Long[] ids, Integer dataState) {
        try {
            //1.校验
            if (ids == null) {
                throw new ParamsErrorException("不良现象类型id不能为空");
            }
            if (dataState == null) {
                throw new ParamsErrorException("不良现象类型状态不能为空");
            }
            //判断当前是否包含子类
            int flag = badphenoTypeMapper.countByBadphenoTypePid(ids);
            if (flag > 0) {
                throw new ParamsErrorException("当前不良现象类下含有子集");
            }
            int row = 0;
//            int row1 = blyyMapper.deleteByblyytypePids(deteBlyytype);
            for (Long i : ids) {
                Badpheno badpheno = new Badpheno();
                badpheno.setBadphenoTypeId(i.intValue());
                int row1 = badphenoMapper.countBadpheno(badpheno);
                if (row1 == 0) {
                    row = badphenoTypeMapper.deleteBadphenoType(ids, dataState);
                } else {
                    throw new ParamsErrorException("该不良现象类型下还有关联的不良现象");
                }
            }
//            int row = badphenoTypeMapper.deleteBlxxtype(deteBlxxtype, lDataState);
            String msg = "";
            switch (dataState) {
                case 1:
                    msg = "启用";
                    break;
                case 2:
                    msg = "删除";
                    break;
                case 3:
                    msg = "停用";
            }
            if (row == 0) {
                // 判断传入的数据状态参数lDataState,返回相应信息
                switch (dataState) {
                    case 1:
                        throw new ModifyFailedException(msg + "失败");
                    case 2:
                        throw new ModifyFailedException(msg + "失败");
                    case 3:
                        throw new ModifyFailedException(msg + "失败");
                }
            }
            return JSONObject.oK(msg + "成功", row);
        } catch (GlobalException e) {
            logger.error(e.getMessage());
            return JSONObject.build(500, e.getMessage());
        }
    }

    //树
    @Override
    public JSONObject treeBadphenoType(BadphenoType badphenoType) {
        List<XTreeNode> tree = new ArrayList<>();
        try {
            List<XTreeNode> nodes = new ArrayList<>();
            List<BadphenoType> list = badphenoTypeMapper.selectAllBadphenoType(badphenoType);
            //获取树的信息
            if(badphenoType.getFlag()!=null) {
                //插入全部
                if(badphenoType.getBadphenoTypeId()==null){
                    BadphenoType badphenoType1 = new BadphenoType();
                    badphenoType1.setBadphenoTypeId(0);
                    badphenoType1.setBadphenoTypePid(0);
                    badphenoType1.setBadphenoTypeName("全部");
                    list.add(0,badphenoType1);
                }
                //生成树list
                List<XTreeNode> treelist = new ArrayList<>();
                for (BadphenoType _MouldType : list) {
                    XTreeNode node = new XTreeNode();
                    node.setId(_MouldType.getBadphenoTypeId());
                    node.setpId(_MouldType.getBadphenoTypePid());
                    node.setTitle(_MouldType.getBadphenoTypeName());
                    treelist.add(node);
                }
                XTreeUtil xTreeUtil = new XTreeUtil(badphenoType.getFlag(), treelist);
                //获取父类
                List<Integer>  parents=xTreeUtil.getParents();
                if (null != list) {
                    for (BadphenoType _MouldType : list) {
                        XTreeNode node = new XTreeNode();
                        node.setId(_MouldType.getBadphenoTypeId());
                        node.setpId(_MouldType.getBadphenoTypePid() == 0 ? null : _MouldType.getBadphenoTypePid());
                        if(parents.contains(_MouldType.getBadphenoTypeId())){
                            node.setExpand(true);
                        }
                        if(!badphenoType.getFlag().equals(0)){
                            if(badphenoType.getFlag().equals(_MouldType.getBadphenoTypeId())){
                                node.setSelected(true);
                            }
                        }
                        node.setTitle(_MouldType.getBadphenoTypeName());
                        nodes.add(node);
                    }
                }
                tree = XCommonUtil.getTree(nodes, null);
                if(badphenoType.getFlag().equals(0)){
                    tree.get(0).setSelected(true);
                }
            }else{
                if (null != list) {
                    for (BadphenoType _MouldType : list) {
                        XTreeNode node = new XTreeNode();
                        node.setId(_MouldType.getBadphenoTypeId());
                        node.setpId(_MouldType.getBadphenoTypePid() == 0 ? null : _MouldType.getBadphenoTypePid());
                        node.setTitle(_MouldType.getBadphenoTypeName());
                        nodes.add(node);
                    }
                }
                tree = XCommonUtil.getTree(nodes, null);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JSONObject.oK(tree);
    }

    //验证重复
    private JSONObject checkParamsNotRepeat(BadphenoType badphenoType) {
        try {
            // 判断不良现象类型ID是否传入
            BadphenoType check = new BadphenoType();
            check.setBadphenoTypeName(badphenoType.getBadphenoTypeName());
            if (badphenoType.getBadphenoTypeId() != null) {
                // 有SOP基础资料ID为更新操作,调用剔除本条记录是否有重复
                check.setBadphenoTypeId(badphenoType.getBadphenoTypeId());
                int row = badphenoTypeMapper.countParamsNotRepeat(check);
                if (row > 0) {
                    throw new ParamsErrorException("已存在该产品");
                }
            } else {
                int row = badphenoTypeMapper.countParamsNotRepeat(check);
                if (row > 0) {
                    throw new ParamsErrorException("已存在该产品");
                }
            }
            return JSONObject.oK();
        } catch (GlobalException e) {
            // 捕获异常,打印并返回
            logger.error(e.getMessage(), e);
            return JSONObject.build(500, e.getMessage());
        }
    }

    //非空判断
    private void validate(BadphenoType badphenoType) {
        //类型名称
        String badphenoTypeName = badphenoType.getBadphenoTypeName();
        if (StringUtils.isEmpty(badphenoTypeName)) {
            throw new ParamsErrorException("类型名称不能为空");
        }
        if (("全部").equals(badphenoType.getBadphenoTypeName())) {
            throw new ParamsErrorException("该不良现象类别名称已存在");
        }
        if (badphenoTypeName.getBytes().length > 50) {
            throw new ParamsErrorException("类型名过长");
        }
        Integer typePid = badphenoType.getBadphenoTypePid();
//        if (typePid == null) {
//            throw new ParamsErrorException("不良原因类型父级不能为空");
//        }
        String remark = badphenoType.getRemark();
        if(remark!=null) {
            if (remark.getBytes().length > 100) {
                throw new ParamsErrorException("说明过长");
            }
        }
    }

    /**
     * 去添加查询树
     * @param badphenoType
     * @return
     */
    @Override
    public JSONObject treeBadphenoTypeToInsert(BadphenoType badphenoType) {
        List<XTreeNode> tree = new ArrayList<>();
        try {
            List<XTreeNode> nodes = new ArrayList<>();
            List<BadphenoType> list = badphenoTypeMapper.selectAllBadphenoTypeToInsert(badphenoType);
            //获取树的信息
            if(badphenoType.getFlag()!=null) {
                //插入全部
                if(badphenoType.getBadphenoTypeId()==null){
                    BadphenoType badphenoType1 = new BadphenoType();
                    badphenoType1.setBadphenoTypeId(0);
                    badphenoType1.setBadphenoTypePid(0);
                    badphenoType1.setBadphenoTypeName("全部");
                    list.add(0,badphenoType1);
                }
                //生成树list
                List<XTreeNode> treelist = new ArrayList<>();
                for (BadphenoType _MouldType : list) {
                    XTreeNode node = new XTreeNode();
                    node.setId(_MouldType.getBadphenoTypeId());
                    node.setpId(_MouldType.getBadphenoTypePid());
                    node.setTitle(_MouldType.getBadphenoTypeName());
                    treelist.add(node);
                }
                XTreeUtil xTreeUtil = new XTreeUtil(badphenoType.getFlag(), treelist);
                //获取父类
                List<Integer>  parents=xTreeUtil.getParents();
                if (null != list) {
                    for (BadphenoType _MouldType : list) {
                        XTreeNode node = new XTreeNode();
                        node.setId(_MouldType.getBadphenoTypeId());
                        node.setpId(_MouldType.getBadphenoTypePid() == 0 ? null : _MouldType.getBadphenoTypePid());
                        if(parents.contains(_MouldType.getBadphenoTypeId())){
                            node.setExpand(true);
                        }
                        if(!badphenoType.getFlag().equals(0)){
                            if(badphenoType.getFlag().equals(_MouldType.getBadphenoTypeId())){
                                node.setSelected(true);
                            }
                        }
                        node.setTitle(_MouldType.getBadphenoTypeName());
                        nodes.add(node);
                    }
                }
                tree = XCommonUtil.getTree(nodes, null);
                if(badphenoType.getFlag().equals(0)){
                    tree.get(0).setSelected(true);
                }
            }else{
                if (null != list) {
                    for (BadphenoType _MouldType : list) {
                        XTreeNode node = new XTreeNode();
                        node.setId(_MouldType.getBadphenoTypeId());
                        node.setpId(_MouldType.getBadphenoTypePid() == 0 ? null : _MouldType.getBadphenoTypePid());
                        node.setTitle(_MouldType.getBadphenoTypeName());
                        nodes.add(node);
                    }
                }
                tree = XCommonUtil.getTree(nodes, null);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JSONObject.oK(tree);
    }
}
